﻿using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using WebsiteForWorkFlow.Data;

namespace WebsiteForWorkFlow
{
    public class WorkFlowTool
    {
        DataInstance _dataInstance;
        public WorkFlowTool(DataInstance dataInstance)
        {
            _dataInstance = dataInstance;
        }
        public static bool StartWorkFlow(Dictionary<string, string> workFlowDirectory)
        {
            DataInstance.AppendMessage("Start: StartWorkFlow");
            DataInstance.AppendMessage(workFlowDirectory);
            HttpClient httpClient = new HttpClient();
            string str = SerializeJson<Dictionary<string, string>>(workFlowDirectory);
            var content = new StringContent(str);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpResponseMessage message = httpClient.PostAsync("http://localhost:8890/api/WorkFlow/RunWorkFlow", content).Result;
            bool result = message.StatusCode == System.Net.HttpStatusCode.OK;
            if (result)
            {
                bool backResult = message.Content.ReadAsAsync<bool>().Result;
                if (backResult)
                {
                    DataInstance.AppendMessage("StartWorkFlow success ");
                }
                else
                    DataInstance.AppendMessage("StartWorkFlow fail");
            }
            else
            {
                DataInstance.AppendMessage("StartWorkFlow fail");
            }
            return result;
        }

        public static bool TaskIsCompleted(Dictionary<string, string> workFlowDictionary)
        {
            DataInstance.AppendMessage("Start: TaskIsCompleted");
            DataInstance.AppendMessage(workFlowDictionary);
            HttpClient httpClient = new HttpClient();
            dynamic dy = new Dictionary<string, string>();
            foreach (string key in workFlowDictionary.Keys)
            {
                dy[key] = workFlowDictionary[key];
            }
            string str = SerializeJson<dynamic>(workFlowDictionary);

            var content = new StringContent(str);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpResponseMessage message = httpClient.PostAsync("http://127.0.0.1:8890/api/WorkFlow/TaskIsComplete", content).Result;
            bool result = message.StatusCode == System.Net.HttpStatusCode.OK;
            if (result)
            {
                bool backResult = message.Content.ReadAsAsync<bool>().Result;
                if (backResult)
                {
                    DataInstance.AppendMessage("TaskIsCompleted success");
                }
                else
                    DataInstance.AppendMessage("TaskIsCompleted fail");
            }
            else
            {
                DataInstance.AppendMessage("TaskIsCompleted fail");
            }
            return result;
        }


        public static List<WorkFlowDetail> GetAllViews()
        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage message = httpClient.GetAsync($"http://127.0.0.1:8890/api/WorkFlow/GetAllViews").Result;
            if (message.IsSuccessStatusCode)
            {
                List<WorkFlowDetail> result = message.Content.ReadAsAsync<List<WorkFlowDetail>>().Result;
                return result;
            }
            return null;
        }
        public static List<ParameterEntity> GetParameterByDetailID(string detailID)
        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage message = httpClient.GetAsync($"http://127.0.0.1:8890/api/WorkFlow/GetParameterByDetailID?detailID={detailID}").Result;
            if (message.IsSuccessStatusCode)
            {
                List<ParameterEntity> result = message.Content.ReadAsAsync<List<ParameterEntity>>().Result;
                return result;
            }
            return null;
        }

        public static WorkFlowFile GetViewConfig(string detailID)
        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage message = httpClient.GetAsync($"http://127.0.0.1:8890/api/WorkFlow/GetViewConfig?detailID={detailID}").Result;
            if (message.IsSuccessStatusCode)
            {
                WorkFlowFile result = message.Content.ReadAsAsync<WorkFlowFile>().Result;
                return result;
            }
            return null;
        }

        public static string HttpPost(string url, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        public static string SerializeJson<T>(T obj, int indentation = 0, char indentchar = ' ')
        {
            StringWriter writer = new StringWriter();
            JsonTextWriter jsoonWriter = new JsonTextWriter(writer)
            {
                Formatting = Formatting.Indented,
                Indentation = indentation,
                IndentChar = indentchar
            };
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(jsoonWriter, obj);
            return writer.ToString();
        }
        public static T DeserializeJson<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
        public static void SendOutData(string result)
        {

        }


    }
}
